package org.leetcode.middle.leetcode146;

import java.util.HashMap;
import java.util.Map;

public class LRUCache3 {

    class Node{
        int val,key;
        Node next,prev;
        public Node(int key,int val){
            this.val=val;
            this.key=key;
        }
    }

    Node dummy = new Node(0,0);
    Map<Integer,Node> map = new HashMap<>();
    final int capacity ;
    public LRUCache3(int capacity) {
        this.capacity=capacity;
        dummy.next=dummy;
        dummy.prev=dummy;
    }

    public int get(int key) {
        Node node = getNode(key);
        if (node==null){
            return -1;
        }
        return node.val;
    }

    public void put(int key, int value) {
        Node node = getNode(key);
        if (node!=null){
            node.val=value;
            return;
        }
        Node newNode = new Node(key, value);
        map.put(key,newNode);
        putHeader(newNode);

        if (map.size()>capacity){
            map.remove(dummy.prev.key);
            removeNode(dummy.prev);
        }
    }
    
    public Node getNode(int key){
      if (!map.containsKey(key)){
          return null;
      }

      Node currNode = map.get(key);

      //1、先将节点在原来的位置进行删除
      removeNode(currNode);
      // 2、将操作的节点放到头部
      putHeader(currNode);
      return currNode;
    }

    public void putHeader(Node node){
        node.next=dummy.next;
        node.prev=dummy;

        dummy.next=node;
        node.next.prev=node;
    }

    public void removeNode(Node node){
        node.prev.next=node.next;
        node.next.prev=node.prev;
    }

}
